import { baseUrl } from "@/common/config";  // Fix path reference
import { generateSignature, generateSignatureWithSecret } from '@/utils/sign';
import { RSAUtil } from '@/utils/rsa';
import { RSA } from '@/utils/crypto';
import RSASegmentCrypto from '@/utils/rsa-segment-crypto.js'


// 创建HTTP实例
class HttpClient {
  constructor(baseURL) {
    this.baseURL = baseURL;
    this.requestInterceptors = [];
    this.responseInterceptors = [];
  }

  // 添加请求拦截器
  addRequestInterceptor(interceptor) {
    this.requestInterceptors.unshift(interceptor);
    return this;
  }

  // 添加响应拦截器
  addResponseInterceptor(interceptor) {
    this.responseInterceptors.push(interceptor);
    return this;
  }

  async request(url, options = {}) {
    let config = {
      url,
      baseURL: this.baseURL,
      method: 'GET',
      header: {},
      ...options
    };

    // 执行请求拦截器（修改为uni兼容格式）
    for (const interceptor of this.requestInterceptors) {
      config = await interceptor(config) || config;
    }

    try {
      // 替换fetch为uni.request（新增完整URL拼接）
      const fullUrl = config.baseURL + config.url;
      const [error, res] = await new Promise(resolve => {
        uni.request({
          ...config,
          url: fullUrl,
          success: res => resolve([null, res]),
          fail: err => resolve([err, null])
        });
      });

      if (error) throw error;
      
      // 执行响应拦截器（适配uni响应格式）
      let response = res;
      for (const interceptor of this.responseInterceptors) {
        response = await interceptor(response) || response;
      }

      return response.data;
    } catch (error) {
      console.error('[HTTP Error]', error);
      throw error;
    }
  }

  // 新增快捷方法（支持链式调用）
  get(url, params) {
    return this.request(url, { method: 'GET', data: params });
  }

  post(url, data) {
    return this.request(url, { method: 'POST', data });
  }
}

// 创建实例并添加通用配置
const http = new HttpClient(baseUrl);

// 示例：添加全局请求头
http.addRequestInterceptor(config => {
  
  // 添加签名到请求头（可根据需要修改）
  config.header['Authorization'] = uni.getStorageSync("token");
  config.header['App-Channel'] = "1";
  config.header['App-Version'] = "1";
  config.header['Api-Version'] = "20250527";
  config.header['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36';
  // config.header['User-Agent'] = 'appName=' + uni.getSystemInfoSync("appName") + ';appVersion=' +uni.getSystemInfoSync("appVersion") 
		// 		+ ';osName=' + uni.getSystemInfoSync("osName") + ';osVersion=' + uni.getSystemInfoSync("osVersion");
  config.header['Device-Id'] = uni.getDeviceInfo().deviceId;
  config.header['ClientTime'] = new Date().getTime();
  config.header['App-Language'] = uni.getStorageSync("app_language") ? uni.getStorageSync("app_language"): "en";
  config.header['Yd-Device-Id'] = '9jfcOPloNhRAHRRFFAbAwh9QG411x/is'; //uni.getDeviceInfo().deviceId;
  config.header['ReleaseVersion'] = 21;
  
  // 生成签名特征字符串
  const signature = generateSignature(config.header, config.data);
  config.header['Signature'] = signature;
  // Fix header setting for uni-app
  config.header = {
    ...config.header,
    Authorization: uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
  };
  return config;
});

// 修改响应拦截器示例（适配uni响应结构）
http.addResponseInterceptor(async response => {
  if (response.statusCode !== 200) {
    await uni.showToast({ title: `请求错误：${response.data.message}` });
  } else {
 //    const rsa = new RSAUtil();
	// let body = rsa.publicDecrypt(response.data)
	// console.log(body)
	const rsaCrypto = new RSASegmentCrypto(1024);
	this.decryptedResult = rsaCrypto.verifyWithPublicKey(
	  response.data, 
	  'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqYDnNgGpi8s5FR3d9ASco08WZFd5HNE+oAYFgr5nFRNPScV0DqXLU9oM+eeW0cyRmnh+WfrCUL2cUopwns4wv0O9lM93Ljaiskfjrwrrred7G82AAt6UfQNmheOcrQrKLU8znzDQ3N8cO6cD1CbuWgKB2JlndxotJFhO5OK4avwIDAQAB'
	);
  }
  return response.data;
});

// 确保在导出前挂载到uni对象
if (!uni.$http) {
  uni.$http = http;
}

export default http;